#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
    typedef pair<int, int> PII;
public:
    int numEnclaves(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size();
        int dr[] = { -1,1,0,0 }, dc[] = { 0,0,-1,1 };
        vector<vector<bool>> vis(m, vector<bool>(n, false));
        queue<PII> q;
        for (int i = 0; i < m; i++) {
            if (grid[i][0] == 1) {
                q.push({ i, 0 });
                vis[i][0] = 1;
            }
            if (grid[i][n - 1] == 1) {
                q.push({ i, n - 1 });
                vis[i][n - 1] = 1;
            }
        }
        for (int j = 0; j < n; j++) {
            if (grid[0][j] == 1) {
                q.push({ 0, j });
                vis[0][j] = 1;
            }
            if (grid[m - 1][j] == 1) {
                q.push({ m - 1, j });
                vis[m - 1][j] = 1;
            }
        }
        while (!q.empty()) {
            int ct = q.size();
            while (ct--) {
                auto [r, c] = q.front();
                grid[r][c] = 2;
                q.pop();
                for (int i = 0; i < 4; i++) {
                    int nr = r + dr[i], nc = c + dc[i];
                    if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == 1 && !vis[nr][nc]) {
                        q.push({ nr, nc });
                        vis[nr][nc] = 1;
                    }
                }
            }
        }
        int ret = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    ret++;
                }
            }
        }
        return ret;
    }
};